﻿using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace StockTradTest.Data
{
    public class StockInfoDataBase
    {
        readonly SQLiteAsyncConnection _database;

        public StockInfoDataBase(string dbPath)
        {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<StockInfo>().Wait();
        }
        public Task<StockInfo> GetStockInfoAsync(string code)
        {
            return _database.Table<StockInfo>()
                            .Where(i => i.Code == code)
                            .FirstOrDefaultAsync();
        }
        public Task<List<StockInfo>> GetAllStockInfoAsync()
        {
            return _database.Table<StockInfo>().
                ToListAsync();
        }
        //储存所有的股票信息索引表
        public async Task<int> SaveAllStockInfoAsync(List<StockInfo> stockInfos)
        {
            List<string> stockNames = new List<string>();
            for (int i = stockInfos.Count - 1;i >= 0; i--)
            {
                StockInfo checkInfo = GetStockInfoAsync(stockInfos[i].Code).Result;
                if(checkInfo != null)
                {
                    stockInfos.RemoveAt(i);
                }
                else
                {
                    stockNames.Add(stockInfos[i].Code);
                }
            }
            WashStockInfoAsync(stockNames);
            return await _database.InsertAllAsync(stockInfos);
        }
        //删除已作废的股票信息
        void WashStockInfoAsync(List<string> stockNames)
        {
            //获取现有的股票信息索引表
            List<StockInfo> oldStockInfos = GetAllStockInfoAsync().Result;
            for (int i = oldStockInfos.Count - 1; i >= 0; i--)
            {
                //删除最新表中没有的股票信息
                if(!stockNames.Contains(oldStockInfos[i].Code))
                {
                    _database.Table<StockInfo>()
                            .Where(j => j.Code == oldStockInfos[i].Code)
                            .DeleteAsync();
                }

            }
        }
    }
}
